/*
 *  Copyright (c) 2011 Leibniz Institute of Plant Genetics and Crop Plant Research (IPK), Gatersleben, Germany.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the GNU Lesser Public License v2.1
 *  which accompanies this distribution, and is available at
 *  http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 *  Contributors:
 *      Leibniz Institute of Plant Genetics and Crop Plant Research (IPK), Gatersleben, Germany - RMI Client, FileChooser and WebDAV
 */
package de.ipk_gatersleben.bit.bi.edal.webdav.sample;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Properties;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.log4j.Logger;
import org.apache.log4j.helpers.Loader;
import org.apache.log4j.xml.DOMConfigurator;
import org.eclipse.jetty.http.ssl.SslContextFactory;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.server.ssl.SslSocketConnector;
import org.eclipse.jetty.webapp.WebAppContext;

import de.ipk_gatersleben.bit.bi.edal.primary_data.EdalConfiguration;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.ClientDataManager;
import de.ipk_gatersleben.bit.bi.edal.webdav.wrapper.FileSystemCache;

/**
 * Main class to start a WebDAV server with an embedded jetty servlet. <br/>
 * Similar to "mvn jetty:run"
 * 
 * @author arendd
 */

@SuppressWarnings("unused")
public class Main {

	private static int EDAL_PORT = 0;
	private static String EDAL_HOST = "";
	private static int WEBDAV_SSLPORT = 8443;

	public static void main(String[] args) {

		final Properties prop = new Properties();

		/* load default webDAV-Properties */
		try {
			prop.load(Main.class.getResourceAsStream("/eDALwebDAV.properties"));
			EDAL_HOST = prop.getProperty("server.host");
			EDAL_PORT = Integer.parseInt(prop.getProperty("server.port"));
			WEBDAV_SSLPORT = Integer.parseInt(prop
					.getProperty("browser.sslport"));
		} catch (final IOException e) {
			ClientDataManager.logger.fatal(
					"error loading default WebDAV properties", e);
			System.exit(-1);
		}

		Options options = new Options();

		System.out
				.println("e!DAL WebDAV server\nCopyright (c) 2012, IPK-Gatersleben.\nAll rights reserved.\n");

		System.out.println("WebDAV-Client ready and listening at port : "
				+ WEBDAV_SSLPORT + "\n");

		options.addOption("h", "help", false, "print help");
		options.addOption("p", "server_port", true,
				"set port for e!DAL server (default=" + EDAL_PORT + ")");

		options.addOption("d", "webdav_port", true,
				"set SSL port for WebDAV server (default=" + WEBDAV_SSLPORT
						+ ")");

		options.addOption("s", "server_host", true,
				"set host for e!DAL server (default=" + EDAL_HOST + ")");

		HelpFormatter form = new HelpFormatter();

		final CommandLineParser parser = new PosixParser();
		CommandLine cmd = null;
		try {
			cmd = parser.parse(options, args);
		} catch (final ParseException e) {
			e.printStackTrace();
		}
		if (cmd.hasOption("h")) {
			form.printHelp("-h", options);
			System.exit(0);
		}
		if (cmd.hasOption("s")) {
			System.setProperty("edalhost", cmd.getOptionValue("s"));
		}
		if (cmd.hasOption("p")) {
			System.setProperty("edalport", cmd.getOptionValue("p"));
		}
		if (cmd.hasOption("d")) {
			WEBDAV_SSLPORT = Integer.parseInt(cmd.getOptionValue("d"));
		}

		Server server = new Server(WEBDAV_SSLPORT);
		WebAppContext context = new WebAppContext();

		SslContextFactory sslContextFactory = new SslContextFactory();

		sslContextFactory.setKeyStorePassword(EdalConfiguration.KEYSTORE_PASSWORD);
		sslContextFactory.setKeyStore(EdalConfiguration.KEY_STORE_PATH.toString());

		SslSocketConnector sslConnector = new SslSocketConnector(
				sslContextFactory);
		sslConnector.setPort(WEBDAV_SSLPORT);

		/*
		 * To accept connection from 8080, otherwise the normal connection
		 * cannot be passed into 8080
		 */

		// SelectChannelConnector selectChannelConnector = new
		// SelectChannelConnector();
		// selectChannelConnector.setPort(WEBDAV_PORT);

		// server.setConnectors(new Connector[]
		// {sslConnector,selectChannelConnector});

		server.setConnectors(new Connector[] { sslConnector });

		/*
		 * default values :
		 * context.setDescriptor("src/main/webapp/WEB-INF/web.xml");
		 * context.setResourceBase("src/main/webapp");
		 */

		try {
			context.setDescriptor(URLDecoder.decode(
					Loader.getResource("WEB-INF/web.xml").toExternalForm(),
					"UTF-8"));
			context.setResourceBase(URLDecoder.decode(
					Loader.getResource("WEB-INF/web.xml").toExternalForm(),
					"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			ClientDataManager.logger.fatal(e.getMessage());
		}

		context.setContextPath("/");
		context.setParentLoaderPriority(true);
		server.setHandler(context);

		try {
			ClientDataManager.logger.info("Start WebDAV server");
			ClientDataManager.logger.info("e!DAL host : " + EDAL_HOST);
			ClientDataManager.logger.info("e!DAL port : " + EDAL_PORT);
			ClientDataManager.logger.info("WebDAV port : " + WEBDAV_SSLPORT);
			server.start();

			FileSystemCache.init();

			server.join();
			
			ClientDataManager.logger.info("WebDAV server started");
		} catch (Exception e) {
			ClientDataManager.logger.fatal("error start jetty server", e);
		}
	}
}
